/*
 * Copyright (c) 2012 Android Dev Freelancer Team. All Rights Reserved.
 */
package com.devgroupvn.dota;

import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.devgroupvn.dota.youtube.MyMediaController;
import com.devgroupvn.dota.youtube.MyVideoView;
import com.devgroupvn.dota.youtube.Vid;
import com.devgroupvn.dota.youtube.VidLinkRetriever;

/* 
 * @class ViewPost
 * @author tkminh
 * @version 1.0, 26 May 2012
 * 
 */

public class ViewPost extends Activity implements OnBufferingUpdateListener, OnCompletionListener, OnPreparedListener
{

	public MediaPlayer mPlayer;
	public SurfaceView mPreview;
	public SurfaceHolder holder;
	public WebView mWebView;
	MyVideoView _videoView;
	
	private ProgressBar _loadingBar;
	private TextView _streaming;
	private FrameLayout _layoutVideo;
	private FrameLayout _layoutVideoForTouch;
	private LinearLayout _layoutPlayerController;
	

	DisplayMetrics displaymetrics = new DisplayMetrics();

	int height;
	int width;
	public String src = "http://static.ec.own3d.tv/embed/3.2.2.8/flowplayer.swf?config=http://www.own3d.tv/inc/flowplayer/embed/json_cfg.php?video_id=645742&1_3";
	String test = "http://o-o.preferred.fpt-sgn1.v9.lscache5.c.youtube.com/videoplayback?upn=O56fFfhxxZs&sparams=cp%2Cid%2Cip%2Cipbits%2Citag%2Cratebypass%2Csource%2Cupn%2Cexpire&fexp=912405%2C919107%2C909912%2C910218%2C907217%2C907335%2C921602%2C919306%2C919316%2C912804%2 913542%2C919324%2C912706&ms=au&itag=18&ip=118.0.0.0&signature=6B3768AAA4DF163FDC70F28F6B4B36AA52D328FD.138A9C401A0F87FC116E0065CB7EC46EA051E948&sver=3&mt=1338625809&ratebypass=yes&source=youtube&expire=1338647930&key=yt1&ipbits=8&cp=U0hSTVZPVV9ISkNOMl9OSVlKOnc1NG13RVFfOUxV&id=1bfb2ec9c353c00d";

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_video);
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		height = displaymetrics.heightPixels;
		width = displaymetrics.widthPixels;
		
		_videoView = (MyVideoView)findViewById(R.id.videoview);
		_loadingBar = (ProgressBar) findViewById(R.id.loadingIcon);
		_streaming = (TextView) findViewById(R.id.streaming);
		_layoutVideo = (FrameLayout) findViewById(R.id.layoutVideo);
		_layoutVideoForTouch = (FrameLayout) findViewById(R.id.layoutVideoForTouch);
		_layoutPlayerController = (LinearLayout) findViewById(R.id.playerController);
		
		MyMediaController _controller = new MyMediaController(this, getWindow(), getWindowManager(), _layoutVideoForTouch, _layoutPlayerController);
		_videoView.setMediaController(_controller);
		
		
		Bundle bundle = getIntent().getExtras();
		String path = "";
		if (bundle != null)
		{
			String link = bundle.getString("link");
			try
			{
				path = new WebContent().getPostContent(link);
//				Intent intent = new Intent(Intent.ACTION_VIEW);
//				intent.setDataAndType(Uri.parse(path), "video/*");
//				playVideo(path);
				playVideoWithLink(path);
//				startActivity(intent);
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
		
//		  MediaController mc = new MediaController(this);
//		  MediaController.p
//		  MediaPlayerControl
//		  _controller.setAnchorView(myVideoView); 
//		  _controller.setMediaPlayer(myVideoView);
//		  myVideoView.setVideoURI(Uri.parse(path));
		
//		  myVideoView.showContextMenu();
//		  myVideoView.requestFocus(); myVideoView.start();
		 

	}
	GetLinkAsyncTask task;
	private void playVideo(String link)
	{
		task = new GetLinkAsyncTask();
//		_loadingBar.setVisibility(ProgressBar.VISIBLE);
//		_streaming.setVisibility(TextView.INVISIBLE);
		task.execute(link);
	}
	private class GetLinkAsyncTask extends AsyncTask<String, Void, List<Vid>>
	{

		@Override
		protected List<Vid> doInBackground(String... params)
		{
			List<Vid> result = null;
			try
			{
				result = VidLinkRetriever.retrieveMP4(params[0]);
			}
			catch (Exception e)
			{
				Log.d("Get Link Youtube", "Error get link MP4");
			}
			return result;
		}

		@Override
		protected void onPostExecute(List<Vid> result)
		{
			super.onPostExecute(result);
			if (result != null)
			{
				if (result.size() > 0)
				{
					int k = getResources().getDisplayMetrics().widthPixels;
					int m = getResources().getDisplayMetrics().heightPixels;
					// if (m == 1024 || k == 1024)
					// playVideoWithLink(result.get(result.size() - 1)
					// .getLink());
					// else
					playVideoWithLink(result.get(0).getLink());
				}
				else
				{
					Log.d("Get Link Youtube", "Couldn't get link MP4");
				}
			}
			else
			{
				Log.d("Get Link Youtube", "Result == NULL");
			}
		}
	}
	private void playVideoWithLink(String link)
	{
		Uri uri = Uri.parse(link);
		_videoView.setVideoURI(uri);
		// _videoView.requestFocus();
		_videoView.start();
	}
	private class webviewclient extends WebViewClient
	{
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url)
		{
			return false;
		}
	}

	private class WebChrome extends WebChromeClient
	{

		@Override
		public void onProgressChanged(WebView view, int newProgress)
		{
			super.onProgressChanged(view, newProgress);
		}

		@Override
		public void onShowCustomView(View view, CustomViewCallback callback)
		{
			super.onShowCustomView(view, callback);
			/*
			 * if (view instanceof FrameLayout) { FrameLayout frame =
			 * (FrameLayout) view; if (frame.getFocusedChild() instanceof
			 * VideoView) { VideoView video = (VideoView)
			 * frame.getFocusedChild(); frame.removeView(video);
			 * setContentView(video); // video.setOnCompletionListener(this); //
			 * video.setOnErrorListener(this); video.start(); } }
			 */
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig)
	{
		super.onConfigurationChanged(newConfig);

		/*
		 * if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
		 * getWindow
		 * ().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		 * getWindow() .setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
		 * WindowManager.LayoutParams.FLAG_FULLSCREEN);
		 * 
		 * myVideoView.setDimensions(height, width);
		 * myVideoView.getHolder().setFixedSize(height, width);
		 * 
		 * } else {
		 * getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN
		 * , WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		 * 
		 * myVideoView.setDimensions(width,
		 * WindowManager.LayoutParams.FILL_PARENT);
		 * myVideoView.getHolder().setFixedSize(width,
		 * WindowManager.LayoutParams.FILL_PARENT);
		 * 
		 * }
		 */
	}

	@Override
	public void onBufferingUpdate(MediaPlayer arg0, int arg1)
	{

	}

	@Override
	public void onCompletion(MediaPlayer arg0)
	{
		// TODO Auto-generated method stub

	}

	@Override
	public void onPrepared(MediaPlayer mp)
	{
		// TODO Auto-generated method stub

	}

}
